package com.company.json;

import org.jsoup.Jsoup;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by v on 17-4-18.
 *
 * 用于储存Json对象
 */
public class Json {
    private String title;
    private List<Floor> list;
    private Floor host;

    public Json(){
        this("");
    }

    public Json(String title){
        this.title=title;
        list=new ArrayList<>();
    }

    public void setList(List<Floor> list) {
        this.list = list;
    }

    public String getTitle() {
        return title;
    }

    public void setHost(Floor host) {
        this.host = host;
    }

    public Floor getHost() {
        return host;
    }

    private String replys(){
        StringBuffer str=new StringBuffer("\"replys\": [");
        for(Floor floor:list){
            String fl="{" +
                    "\"content\": \""+floor.getText()+"\"," +
                    "\"author\": \""+host.getAuthorName()+"\""+
                    "\"title\": \""+title+"\"," +
                    "\"publish_date\": \""+floor.getTime()+"\"" +
                    "}";
            str.append(fl+",");
        }

        str.deleteCharAt(str.length()-1);
        str.append("]");

        return str.toString();
    }

    private String post(){
        StringBuffer str=new StringBuffer("\"post\": {" +
                "\"content\": \""+host.getText()+"\"," +
                "\"author\": \""+host.getAuthorName()+"\""+
                "\"title\": \""+title+"\"," +
                "\"publish_date\": \""+host.getTime()+"\"" +
                "},");

        return str.toString();
    }

    private String json(){
        return "{"+post()+replys()+"}";
    }

    public void outPut(){
        File file=new File("/home/v/IdeaProjects/Teddy/output/"+title);

        try {
            PrintWriter output=new PrintWriter(file);
            output.write(json()+"\n\n");
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
}
